//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by mac on 15/11/28.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    let webview = UIWebView()
    override func loadView() {
        view = webview
        webview.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航条
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultClick")
        //实现跳转,加载页面
        loadOAuthPage()
    }
    
    @objc func defaultClick(){
        let a = "document.getElementById('userId').value='251006783@qq.com',document.getElementById('passwd').value='ww03251562'"
    webview.stringByEvaluatingJavaScriptFromString(a)
        
    }
    @objc private func close(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    private func loadOAuthPage(){
        let urlString = baseurl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        if let url = NSURL(string: urlString){
        let request = NSURLRequest(URL: url)
            //是用webview加载页面
            webview.loadRequest(request)
        }
        
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
}

  //是用extension 为当前类扩展协议方法
    extension OAuthViewController: UIWebViewDelegate{
        func webViewDidFinishLoad(webView: UIWebView){
        //关闭
            SVProgressHUD.dismiss()
        }
        func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.show()
        }
        //协议方法,返回值是bool 如果返回时true 持有协议的对象就可以正常工作.否则就不行
        // URL: https://api.weibo.com/oauth2/authorize?client_id=2661975595&redirect_uri=http://www.baidu.com
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
           
            let urlString = request.URL?.absoluteString ?? ""
            //屏蔽掉不希望的页面
            if urlString.hasPrefix("https://api.weibo.com"){
            return true
            }
            if !urlString.hasPrefix("http://www.baidu.com"){
            return false
            }   
            //获取授权码
            guard let query = request.URL?.query else{
            //获取不到参数列表
                return false
            }
            let codeStr = "code="
            let code = query.substringFromIndex(codeStr.endIndex)
            //获取到用户code,请求token
           UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("联接失败")
                return
            }
        }
            self.dismissViewControllerAnimated(true) { () -> Void in
                //发出切换页面消息
                 NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
            }
            
           
           
            return false
    }
        
//        //请求用户的TOKEN
//        private func loadAccessToken(code: String){
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//            //请求需要的参数
//            let paramenters = ["client_id" : client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
//            let afn = AFHTTPSessionManager()
//            //设置添加反序列户类型
//            afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
//            afn.POST(urlString, parameters: paramenters, success: { (_, result) -> Void in
//                //拿到用户token之后,立即请求用户信息
//                guard let dict = result as?[String: AnyObject] else{
//                  return
//                }
//                let account = UserAccount(dict: dict)
//              
//                //加载用户信息
//                self.loadUserInfo(account)
//                
//                print(result.classForCoder)
//                }) { (_, error) -> Void in
//                print(error)
//            }
//        }
//        
//        
//        
//        private func loadUserInfo(account: UserAccount){
//            let urlString = "https://api.weibo.com/2/users/show.json"
//            //为了保险,先判断
//            guard let access_token = account.access_token,userId = account.uid else{
//                SVProgressHUD.showErrorWithStatus("获取网络数据失败")
//            return
//            }
//            let parameters = ["access_token":access_token,"uid":userId]
//            let afn = AFHTTPSessionManager()
//            afn .GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//                account.avatar_large = result["avatar_large"]as? String
//                account.name = result["name"]as? String
//                //保存信息
//                account.saveAccount()
//                SVProgressHUD.showSuccessWithStatus("登录成功")
//                
//                }) { (_, error) -> Void in
//                    
//                    print(error)
//            }
//        
//        }
    }

